package com.zyasdk.util;

import java.io.File;
import java.io.RandomAccessFile;

import android.os.Environment;

public class FileUtil {
	private static String filePath = Environment.getExternalStorageDirectory()
			.getAbsolutePath() + "/download/";
	private static String fileName = "log.txt";

	public static void writeLog(String strcontent) {
		writeTxtToFile(strcontent, filePath, fileName);
	}

	/**
	 * 将字符串写入到文本文件中
	 * 
	 * @param strcontent
	 * @param filePath
	 * @param fileName
	 */
	public static void writeTxtToFile(String strcontent, String filePath,
			String fileName) {
		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED))
			return;
		// 生成文件夹之后，再生成文件，不然会出错
		makeFilePath(filePath, fileName);
		String strFilePath = filePath + fileName;
		// 每次写入时，都换行写
		String strContent = strcontent + "\r\n";
		try {
			File file = new File(strFilePath);
			if (!file.exists()) {
				file.getParentFile().mkdirs();
				file.createNewFile();
			}
			RandomAccessFile raf = new RandomAccessFile(file, "rwd");
			raf.seek(file.length());
			raf.write(strContent.getBytes());
			raf.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 生成文件
	 * 
	 * @param filePath
	 * @param fileName
	 * @return
	 */
	public static File makeFilePath(String filePath, String fileName) {
		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED))
			return null;
		File file = null;
		makeRootDirectory(filePath);
		try {
			file = new File(filePath + fileName);
			if (!file.exists()) {
				file.createNewFile();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return file;
	}

	/**
	 * 生成文件夹
	 * 
	 * @param filePath
	 */
	public static void makeRootDirectory(String filePath) {
		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED))
			return;
		File file = null;
		try {
			file = new File(filePath);
			if (!file.exists()) {
				file.mkdir();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
